package com.example.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LogAspect {
    // 前置增强：add、delete、find方法执行前
    @Before("execution(* com.example.service.OrderService.*(..))")
    public void beforeAdvice(JoinPoint joinPoint) {
        System.out.println("hello, 我是一个前置增强");
    }

    // 后置增强：add、delete方法执行后
    @AfterReturning("execution(* com.example.service.OrderService.add(..)) || execution(* com.example.service.OrderService.delete(..))")
    public void afterReturningAdvice(JoinPoint joinPoint) {
        System.out.println("bye, 我是一个后置增强");
    }

    // 获取方法返回值并输出：add、delete、find方法
    @AfterReturning(pointcut = "execution(* com.example.service.OrderService.*(..))", returning = "result")
    public void getReturnValue(JoinPoint joinPoint, Object result) {
        System.out.println("方法 " + joinPoint.getSignature().getName() + " 的返回值为: " + result);
    }

    // 输出方法执行时间（毫秒）：add、delete、find方法
    @Around("execution(* com.example.service.OrderService.*(..))")
    public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = pjp.proceed();
        long endTime = System.currentTimeMillis();
        System.out.println("方法 " + pjp.getSignature().getName() + " 执行时间为: " + (endTime - startTime) + " 毫秒");
        return result;
    }
}